var RNFS = require('react-native-fs');
import XLSX from 'xlsx';
import React, { Component } from 'react';
import {
    View,
    Text,
    Image,
    StyleSheet,
    ScrollView,
    SafeAreaView,
    Pressable,
    Alert
} from 'react-native';
import { changeloginStatus, getexam } from '../../../actions/actionCreators'
import store from '../../../store/configureStore'
import RNHTMLtoPDF from 'react-native-html-to-pdf';
import { examinationPDF } from '../../../utils/path'
import  RNPop from '../Home/comments/model'

export default class FriendPage extends Component {
    constructor(props) {
        console.log(store.getState(), props)
        // 监听store的数据更新，可以注销更新，unsubscriobe.
        super(props);
        this.state = {
            item: '',
            score: "",
            newarr: [],
            sliceArr: []
        }
    }
    static navigationOptions = {
        headerShown: false,
        tabBarLabel: '好友',
        tabBarIcon: ({ focused }) => {
            if (focused) {
                return (
                    <Text>这是好友</Text>

                    // <Image style={styles.tabBarIcon} source={require('../../img/fri_sel.png')}/>
                );
            }
            return (
                <Text>这是好友</Text>

                // <Image style={styles.tabBarIcon} source={require('../../img/fri_nor.png')}/>
            );
        },
    };
    componentWillMount() {
        const { params } = this.props.navigation.state;
        // 读取excel文件的题库
        console.log(params)
        let paths = params.data.exampath//题目路径
        let choosecount = params.count//抽选题目
        RNFS.readFile(paths, 'ascii').then(res => {
            console.log(res)
            const workbook = XLSX.read(res, { type: 'binary' });
            console.log(workbook)
            // 读取到保存的excel新文件进行修改字段操作
            var worksheet = workbook.Sheets[workbook.SheetNames[0]];
            var jsondata = XLSX.utils.sheet_to_json(worksheet);
            const sliceArr = jsondata.slice(3)
            // 随机抽特定数量的题choosecount= 5
            const newarr = this.RandomNumBoth(sliceArr, choosecount)
            this.setState({ newarr: newarr, sliceArr: jsondata })

            console.log(jsondata, newarr, sliceArr, this.state.newarr, this.state.sliceArr)
            // jsondata[1]['姓名'] = "李四修改1次"//实际上就是定义的worbook改掉了
            // let changeworksheet = XLSX.utils.json_to_sheet(jsondata)
            // // 转化为json数据修改excel数据后重新写入工作表
            // workbook.Sheets[workbook.SheetNames[0]] = changeworksheet
            // const wbout = XLSX.write(workbook, { type: 'binary', bookType: "xlsx" });
            // RNFS.writeFile(paths, wbout, 'ascii').then((r) => {/* :) */ }).catch((e) => {/* :( */ });
            // console.log(worksheet, workbook)
        })

    }
    RandomNumBoth(arr, maxNum) {
        var numArr = [];
        var arrLength = arr.length;
        for (var i = 0; i < arrLength; i++) {
            var Rand = arr.length;
            //取出随机数 
            var number = Math.floor(Math.random() * arr.length); //生成随机数num是存在的某个索引值
            console.log(number, Math.random())
            numArr.push(arr[number]); //往新建的数组里面传入数值
            arr.splice(number, 1); //传入一个删除一个，避免重复
            if (arr.length <= arrLength - maxNum) {
                return numArr;
            }
        }
    }
    changetiku() {
        var count = this.props.navigation.state.params.count
        const newarr = this.RandomNumBoth(this.state.sliceArr.slice(3), count)
        this.setState({ newarr: newarr })
    }
    createPDF = async () => {
        let html = `<div>
         <h1 style="text-align: center;">${this.props.navigation.state.params.data.title}</h1>
         <p style="text-align: center;">共${this.state.newarr.length}题，每题${100 / this.state.newarr.length}分，总分100分</p>
         <p style="text-align: center;">姓名：————————&nbsp;  &nbsp;  &nbsp;  &nbsp;              联系方式：——————————</p>
        <div style="width: 80%;margin: auto;">
        ${this.state.newarr.map((item, index) => {
            return (`<h4>${index + 1},(${item.topic_type}) ${item.content}</h4>
   
               ${item.chooses.map(item1 => {
                return (item1 && `
                      <p>${item1}</p>
                      `)
            })
                }
                `)
        })
            }    
        </div>`
        // console.log( this.state.newarr,html)
        let options = {
            html: html,
            fileName: this.props.navigation.state.params.data.title,
        };
        RNHTMLtoPDF.convert(options).then((res => {
            console.log(res)
            RNFS.moveFile(res.filePath, examinationPDF + `/${options.fileName}.pdf`)
                .then(() => {
                    console.log('moveFIle Success');
                    Alert.alert('提示', `文档存储路径:${ examinationPDF}`, [
                        { text: '确定', onPress: () => {this.back()} },
                    ]);
                })
                .catch((err) => {
                    console.log('moveFile failed', err);
                });
        })
        )
        // alert(file.filePath);

    }
    back() {
        console.log(1111)
        this.props.navigation.replace('Home', { user: 'Sybil' })
    }
    render() {

        const { navigate } = this.props.navigation;

        return (

            <View style={styles.container}>
                {/* 引入弹窗模板 */}
	         <RNPop ref="rnPop" />
                <View><Text style={{ marginTop: 20, fontSize: 30, fontWeight: 'bold' }}>{this.props.navigation.state.params.data.title}</Text></View>
                <View><Text style={{ marginTop: 10 }}>共{this.state.newarr.length}题，每题{100 / this.state.newarr.length}分，总分100分</Text></View>
                <View style={styles.names}>
                    <View style={styles.a1}>
                        <Text>姓名：</Text>
                        <Text style={{ borderBottomWidth: 1, borderBottomColor: "#000000", width: 100 }}></Text>
                    </View>
                    <View style={styles.a1}>
                        <Text>联系方式：</Text>
                        <Text style={{ borderBottomWidth: 1, borderBottomColor: "#000000", width: 100 }}></Text>
                    </View>
                </View>
                <SafeAreaView style={styles.box}>
                    <ScrollView style={styles.scrollView}>
                        <View>
                            {
                                this.state.newarr.map((item, index) => {
                                    if (item.topic_type == 1) {
                                        item.topic_type = '单选'
                                    } else if (item.topic_type == 2) {
                                        item.topic_type = '多选'
                                    } else if (item.topic_type == 3) {
                                        item.topic_type = '判断'
                                    }
                                    var chooses = ['A  ' + item.content_1, 'B  ' + item.content_2, item.content_3 && 'C  ' + item.content_3, item.content_4 && 'D  ' + item.content_4, item.content_5 && 'E  ' + item.content_5, item.content_6 && 'F  ' + item.content_6]
                                    item.chooses = chooses
                                    return (
                                        <View key={index}>
                                            <View style={styles.title}>
                                                <Text>
                                                    {index + 1}，（{item.topic_type}）{item.content}
                                                </Text>
                                            </View>
                                            <View style={styles.answer}>
                                                {
                                                    item.chooses.map((item1, index1) => {
                                                        if (item1) {
                                                            return (
                                                                <Text key={index1}>{item1}</Text>
                                                            )
                                                        }
                                                    })
                                                }
                                            </View>
                                        </View>
                                    )
                                })
                            }

                        </View>


                    </ScrollView>
                </SafeAreaView>
                <View style={{ width: '85%', flexDirection: 'row', justifyContent: 'flex-end', position: "relative", marginTop: 10 }}>
                    <Pressable
                        style={{ position: 'absolute', left: 10,zIndex:100, }}
                        onPress={() => {
                            this.back()
                        }}

                    >
                        <Text style={{ ...styles.btns, fontSize: 12, color: "#fff", borderRadius: 8 }} >
                            放弃创建
                        </Text>
                    </Pressable>
                    <Pressable
                        onPress={() => { this.changetiku() }}
                    >
                        <Text style={{ ...styles.btns, fontSize: 12, color: "#fff", borderRadius: 8, marginRight: 10 }} >
                            重新生成
                       </Text>
                    </Pressable>
                    <Pressable
                        onPress={() => { this.createPDF() }}
                    >
                        <Text style={{ ...styles.btns, fontSize: 12, color: "#fff", borderRadius: 8, }} >
                            保存试卷
                         </Text>
                    </Pressable>
                </View>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: "#fff"
    },
    tabBarIcon: {
        width: 21,
        height: 21,
    },
    names: {
        flexDirection: "row",
        justifyContent: "space-around",
        marginTop: 5
    },
    a1: {
        flexDirection: "row",
        justifyContent: "space-around",
        padding: 10
    },
    box: {
        flex: 1,
        marginTop: 10,
        width: '90%'
        // marginTop: Constants.statusBarHeight,
    },
    title: {
        marginTop: 10
    },
    scrollView: {
        // backgroundColor: 'pink',
        marginHorizontal: 20
        ,
    },
    text: {
        fontSize: 42,
    },
    btns: {
        backgroundColor: '#46B0E2',
        width: 100,
        height: 30,
        textAlign: 'center',
        lineHeight: 30,
        fontWeight: 'bold'
    }
});